package com.buyouchina.web.action.logon;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

import com.buyouchina.bean.privilege.PrivilegeGroup;
import com.buyouchina.bean.privilege.User;
import com.buyouchina.service.privilege.UserService;
import com.buyouchina.service.product.OutletsService;
import com.buyouchina.utils.SiteUrl;
import com.buyouchina.web.action.BaseAction;
import com.opensymphony.xwork2.ModelDriven;

@Controller
public class LogonAction extends BaseAction implements ModelDriven<User> {

	// 总部地址
	public static final String BASE = "base_index";
	// 店铺选择
	public static final String SELECT = "outlets_select";

	private static final long serialVersionUID = -785341130521536534L;
	private User user = new User();
	@Resource(name = "userServiceBean")
	UserService userService;
	@Resource(name = "outletsServiceBean")
	private OutletsService outletsService;
	private String forward;

	@SuppressWarnings("unchecked")
	@Override
	public String execute() throws Exception {

		// 如果没有空指针
		if (user.getPhone() != null && !"".equals(user.getPhone().trim())
				&& user.getPassword() != null && !"".equals(user.getPassword())) {

			// 如果用户名密码正确
			if (userService.checkUser(user.getPhone(), user.getPassword())) {
				user = userService.findByPhone(user.getPhone().trim());

				// 如果用户被禁用
				if (user.getVisible() == false) {
					request.setAttribute("message", "对不起您的账号已被禁用，无法登陆系统！");
					return INPUT;
				}
				if (session.get("outlets") != null) {
					session.remove("outlets");
				}

				// 如果用户选择登录到总部
				if (forward != null && forward.equals("base")) {
					List<PrivilegeGroup> groupList = new ArrayList<PrivilegeGroup>(
							user.getGroups());
					for (int i = 0; i < groupList.size(); i++) {
						PrivilegeGroup pg = groupList.get(i);
						if (pg.getLevel() > 5000) {

							// 将用户存入session
							session.put("outlets", outletsService.find(1));
							session.put("user", user);
							return BASE;
						}
					}
					request.setAttribute("message", "您没有权限这样做");
					return INPUT;
				} else { // 用户选择登入店铺

					// 将用户存入session
					session.put("user", user);
					return SELECT;
				}
			} else { // 用户名密码错误
				request.setAttribute("message", "用户名或密码错误！");
				request.setAttribute("urladdress", SiteUrl.readUrl("logon"));
				return MESSAGE;
			}
		}
		return INPUT;
	}

	public User getModel() {
		return user;
	}

	public String getForward() {
		return forward;
	}

	public void setForward(String forward) {
		this.forward = forward;
	}
}
